package main

import (
	"flag"
	"github.com/gorilla/mux"
	ahandler "github.com/micro/go-api/handler"
	//aapi "github.com/micro/go-api/handler/api"
	arpc "github.com/micro/go-api/handler/rpc"
	"github.com/micro/go-api/resolver"
	rrmicro "github.com/micro/go-api/resolver/micro"
	"github.com/micro/go-api/router"
	"github.com/micro/go-api/server"
	"github.com/micro/go-log"
	"github.com/micro/go-micro"
	"net/http"
)

var (
	name      = flag.String("name", "yungrun.com.gateway", "name")
	namespace = flag.String("namespace", "go.micro.api", "namespace")
	address   = flag.String("address", ":8080", "listened address")
)

func main() {
	flag.Parse()
	run()
}

func run() {
	var opts []server.Option
	var h http.Handler
	r := mux.NewRouter()
	h = r


	service := micro.NewService(
		micro.Name(*name),
	)


	log.Log(*namespace)
	// register rpc handler
	//log.Logf("Registering RPC Handler at %s", "/rpc")
	//r.HandleFunc("/rpc", handler.RPC)

	ropts := []resolver.Option{
		resolver.WithNamespace(*namespace),
		resolver.WithHandler("meta"),
	}

	rr := rrmicro.NewResolver(ropts...)

	//log.Logf("Registering API Request Handler at %s", "/")
	//rt := router.NewRouter(
	//	router.WithNamespace(*namespace),
	//	router.WithHandler(aapi.Handler),
	//	router.WithResolver(rr),
	//)
	//ap := aapi.NewHandler(
	//	ahandler.WithNamespace(*namespace),
	//	ahandler.WithRouter(rt),
	//	ahandler.WithService(service),
	//)
	//r.PathPrefix("/").Handler(ap)
	log.Logf("Registering API RPC Handler at %s", "/")
	rt := router.NewRouter(
		router.WithNamespace(*namespace),
		router.WithHandler(arpc.Handler),
		router.WithResolver(rr),
	)
	rp := arpc.NewHandler(
		ahandler.WithNamespace(*namespace),
		ahandler.WithRouter(rt),
		ahandler.WithService(service),
	)
	r.PathPrefix("/").Handler(rp)
	api := server.NewServer(*address)
	api.Init(opts...)
	api.Handle("/", h)
	if err := api.Start(); err != nil {
		log.Fatal(err)
	}
	// Run server
	if err := service.Run(); err != nil {
		log.Fatal(err)
	}

	// Stop API
	if err := api.Stop(); err != nil {
		log.Fatal(err)
	}
}
